﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using MathematicallySafe.HeadCounter.Data.Models;
using MathematicallySafe.Armourer.Base;
using StructureMap;

namespace MathematicallySafe.HeadCounter.Data.Common
{
    public static class RaidDateHelper
    {
        private static Dictionary<WowRegion, DayOfWeek> WeekStartDays = new Dictionary<WowRegion, DayOfWeek>()
                                                                        {
                                                                            {WowRegion.US, DayOfWeek.Tuesday},
                                                                            {WowRegion.EU, DayOfWeek.Wednesday}
                                                                        };
                                                                        
        public static DateTime GetWeekStart(this DateTime dateTime, WowRegion region)
        {
            var startDay = WeekStartDays[region];

            while (dateTime.DayOfWeek != startDay)
            {
                dateTime = dateTime.AddDays(-1);
            }

            return dateTime;
        }

        
        public static int GetWeekNumber(this DateTime dateTime, WowRegion region)
        {
            CultureInfo culture = CultureInfo.CurrentCulture;
            return culture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFullWeek, WeekStartDays[region]);
        }

        public static int GetWeekNumber(this DateTime dateTime)
        {
            var culture = CultureInfo.CurrentCulture;

            var raidHistory = ObjectFactory.GetInstance<IHeadCounterService>().RaidHistory;
            var weekOneDate = raidHistory.WeekOneDate;

            var weekStartDate = dateTime;
            while (weekStartDate.DayOfWeek != weekOneDate.DayOfWeek)
                weekStartDate = weekStartDate.AddDays(-1.0);

            return (weekStartDate - weekOneDate).Days / 7;

//            var firstWeekNumber = culture.Calendar.GetWeekOfYear(weekOneDate, CalendarWeekRule.FirstFullWeek, weekOneDate.DayOfWeek);
//            var weekNumber = culture.Calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstFullWeek, weekOneDate.DayOfWeek);
//
//            var yearOffset = -firstWeekNumber;
//            if (dateTime.Year > weekOneDate.Year)
//            {
//                yearOffset = 52 - firstWeekNumber;
//            }
//
//            return weekNumber + yearOffset;
        }
    }
}